<template>
	<view class="post-page">
		<!-- 顶部Tab切换（4大板块） -->
		<view class="plate-tabs">
			<scroll-view scroll-x class="tabs-scroll">
				<view class="tab-list">
					<view 
						v-for="plate in plates" 
						:key="plate.plateId" 
						class="tab-item"
						:class="{ active: selectedPlateId === plate.plateId }"
						:style="{ 
							borderColor: selectedPlateId === plate.plateId ? plate.color : 'transparent',
							color: selectedPlateId === plate.plateId ? plate.color : '#666'
						}"
						@click="handleTabClick(plate.plateId)"
					>
						<text class="tab-name">{{ plate.plateName }}</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 二级分类 -->
		<view class="sub-categories" v-if="subCategories.length > 0">
			<scroll-view scroll-x class="categories-scroll">
				<view class="category-list">
					<view 
						class="category-item"
						:class="{ active: selectedSubCategory === '' }"
						@click="handleSubCategoryClick('')"
					>
						<text class="category-name">全部</text>
					</view>
					<view 
						v-for="sub in subCategories" 
						:key="sub.id" 
						class="category-item"
						:class="{ active: selectedSubCategory === sub.name }"
						@click="handleSubCategoryClick(sub.name)"
					>
						<text class="category-name">{{ sub.name }}</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<view class="post-header">
			<view class="post-search">
				<!-- 搜索栏 -->
				<up-search shape="round" v-model="searchValue" @search="postSearch" @clear="searchClear" :clearabled="true"></up-search>
			</view>
		</view>

		<!-- 帖子列表 -->
		<view class="post-content">
			<!-- 下拉刷新容器 -->
			<scroll-view scroll-y class="scroll-container" @scrolltolower="loadMorePost" :refresher-enabled="true"
				:refresher-triggered="refreshing" @refresherrefresh="onRefresh" @refresherrestore="onRestore">
				
				<!-- 骨架屏 -->
				<view class="skeleton-container" v-if="loading && posts.length === 0">
					<view class="skeleton-item" v-for="i in 3" :key="i">
						<view class="skeleton-content">
							<view class="skeleton-title skeleton-animate"></view>
							<view class="skeleton-meta">
								<view class="skeleton-text skeleton-animate"></view>
								<view class="skeleton-text skeleton-animate"></view>
							</view>
						</view>
					</view>
				</view>

				<!-- 帖子列表 - 根据板块类型使用不同组件 -->
				<view class="posts-container" v-else-if="posts && posts.length > 0">
					<!-- 讨论区和分享区 - 使用postItem，可点击查看详情 -->
					<template v-if="selectedPlateId === 1 || selectedPlateId === 2">
						<PostItem v-for="post in posts" :key="post.postId" :post="post" @click="handlePostClick" />
					</template>

					<!-- 交易区 - 使用tradeItem，点击联系按钮进行联系 -->
					<template v-else-if="selectedPlateId === 3">
						<TradeItem v-for="post in posts" :key="post.postId" :post="post" />
					</template>

					<!-- 求助区 - 使用helpItem，点击联系按钮进行联系 -->
					<template v-else-if="selectedPlateId === 4">
						<HelpItem v-for="post in posts" :key="post.postId" :post="post" />
					</template>

					<!-- 加载更多提示 -->
					<view class="load-more" v-if="hasMore">
						<up-loading-icon v-if="loadingMore" size="20" />
						<text v-else class="load-more-text">上拉加载更多</text>
					</view>
					<view class="no-more" v-else>
						<text class="no-more-text">没有更多了</text>
					</view>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-else-if="!loading && posts.length === 0">
					<up-icon name="file-text" size="80" color="#cccccc"></up-icon>
					<text class="empty-text">暂无内容</text>
					<text class="empty-hint">快来发布第一条内容吧～</text>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { onReachBottom } from '@dcloudio/uni-app';

// 导入组件
import PostItem from './components/postItem.vue';
import TradeItem from './components/tradeItem.vue';
import HelpItem from './components/helpItem.vue';

// 导入Mock服务（子分类暂时使用Mock，后端未实现）
import { mockGetSubCategories } from '../../server/mock.js';

// 导入真实API
import { getPlatesService } from '../../server/api/plate.js';
import { getPostsService } from '../../server/api/post.js';

// 导入数据适配器
import { adaptPlateList, adaptPostList } from '../../utils/dataAdapter.js';

// 路由实例
const router = useRouter();

// 响应式数据
const searchKeyword = ref('');
const selectedPlateId = ref(1); // 默认选择讨论区
const selectedSubCategory = ref(''); // 选中的二级分类
const posts = ref([]);
const plates = ref([]);
const subCategories = ref([]); // 二级分类列表
const isFristGetPosts = ref(true);
const loadMoreText = ref('下拉加载更多');
const loading = ref(true);
const loadingMore = ref(false);
const hasMore = ref(true);
const pageNum = ref(1);
const pageSize = ref(10);
const searchValue = ref('');
const refreshing = ref(false); // 下拉刷新状态

// 监听板块切换，加载对应的二级分类
watch(selectedPlateId, async (newPlateId) => {
	// 重置二级分类选择
	selectedSubCategory.value = '';
	
	// 加载二级分类
	if (newPlateId) {
		await fetchSubCategories(newPlateId);
	}
});

/**
 * 搜索内容
 */
const postSearch = () => {
	pageNum.value = 1;
	isFristGetPosts.value = true;
	hasMore.value = true;
	getPostList();
};

// 页面加载时获取数据
onMounted(() => {
	fetchPlates();
	getPostList();
});

// 绑定页面触底逻辑
onReachBottom(() => {
	loadMorePost();
});

// 获取板块列表
const fetchPlates = async () => {
	try {
		const res = await getPlatesService();
		if (res.code === 200) {
			// 使用数据适配器处理后端板块数据
			plates.value = adaptPlateList(res.data || []);
			
			// 默认加载第一个板块的子分类
			if (plates.value.length > 0) {
				fetchSubCategories(selectedPlateId.value);
			}
		}
	} catch (error) {
		console.error('获取板块失败:', error);
		plates.value = [];
	}
};

// 获取二级分类
const fetchSubCategories = async (plateId) => {
	try {
		const res = await mockGetSubCategories(plateId);
		if (res.code === 200) {
			subCategories.value = res.data || [];
		}
	} catch (error) {
		console.error('获取子分类失败:', error);
		subCategories.value = [];
	}
};

/**
 * 获取帖子列表
 */
const getPostList = async () => {
	if (pageNum.value === 1) {
		loading.value = true;
	}
	
	try {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			plateId: selectedPlateId.value || undefined,
			// 注意：后端暂不支持subCategory，暂时忽略该参数
			// subCategory: selectedSubCategory.value || undefined,
			title: searchValue.value || undefined
		};

		const res = await getPostsService(params);
		
		if (res.code === 200) {
			// 后端直接返回数组，不是{list, total}结构
			let newPosts = [];
			let total = 0;
			
			if (Array.isArray(res.data)) {
				// 使用数据适配器处理帖子数据
				newPosts = adaptPostList(res.data);
				total = res.data.length; // 由于后端没有分页total，暂时用数据长度
			} else if (res.data && res.data.list) {
				// 如果后端返回了分页结构
				newPosts = adaptPostList(res.data.list || []);
				total = res.data.total || 0;
			}

			if (isFristGetPosts.value) {
				posts.value = newPosts;
				isFristGetPosts.value = false;
			} else {
				posts.value.push(...newPosts);
			}

			// 判断是否还有更多数据
			// 如果返回的数据少于pageSize，说明没有更多了
			hasMore.value = newPosts.length >= pageSize.value;
		}
	} catch (error) {
		console.error('获取帖子列表失败:', error);
		if (isFristGetPosts.value) {
			posts.value = [];
		}
	} finally {
		loading.value = false;
	}
};

/**
 * 清除搜索
 */
const searchClear = () => {
	searchValue.value = '';
	pageNum.value = 1;
	isFristGetPosts.value = true;
	hasMore.value = true;
	getPostList();
};

/**
 * Tab点击 - 切换一级板块
 */
const handleTabClick = (plateId) => {
	if (selectedPlateId.value === plateId) return;
	
	selectedPlateId.value = plateId;
	selectedSubCategory.value = '';
	pageNum.value = 1;
	isFristGetPosts.value = true;
	hasMore.value = true;
	getPostList();
};

/**
 * 子分类点击
 */
const handleSubCategoryClick = (categoryName) => {
	if (selectedSubCategory.value === categoryName) return;
	
	selectedSubCategory.value = categoryName;
	pageNum.value = 1;
	isFristGetPosts.value = true;
	hasMore.value = true;
	getPostList();
};

/**
 * 点击帖子
 */
const handlePostClick = (postId) => {
	console.log(postId);
	uni.navigateTo({
		url: `/pages/post/postInfo?postId=${postId}`
	});
};

/**
 * 加载更多帖子
 */
const loadMorePost = () => {
	if (!hasMore.value || loadingMore.value || loading.value) return;
	
	loadingMore.value = true;
	pageNum.value += 1;
	getPostList().finally(() => {
		loadingMore.value = false;
	});
};

/**
 * 下拉刷新
 */
const onRefresh = async () => {
	refreshing.value = true;
	pageNum.value = 1;
	isFristGetPosts.value = true;
	hasMore.value = true;
	
	try {
		await getPostList();
	} finally {
		// 延迟关闭刷新状态，让用户看到刷新动画
		setTimeout(() => {
			refreshing.value = false;
		}, 300);
	}
};

/**
 * 刷新恢复
 */
const onRestore = () => {
	refreshing.value = false;
};

onUnmounted(() => {
	// 清理工作
});
</script>

<style lang="scss" scoped>
@import './styles/post.scss';
@import '../../styles/variables.scss';
@import '../../styles/mixins.scss';

// 板块Tab样式 - 简洁版
.plate-tabs {
	background: $bg-card;
	border-bottom: 1px solid $border-light;
	
	.tabs-scroll {
		white-space: nowrap;
		width: 100%;
		
		.tab-list {
			display: inline-flex;
			padding: 0;
			
			.tab-item {
				flex-shrink: 0;
				padding: $spacing-lg $spacing-xl;
				border-bottom: 2px solid transparent;
				transition: all $transition-base;
				
				.tab-name {
					font-size: $font-base;
					color: $text-secondary;
					font-weight: $font-medium;
					transition: all $transition-fast;
				}
				
				&.active {
					border-bottom-color: $primary-color;
					
					.tab-name {
						color: $primary-color;
						font-weight: $font-semibold;
					}
				}
			}
		}
	}
}

// 二级分类样式 - 简洁版
.sub-categories {
	background: $bg-card;
	padding: $spacing-sm 0;
	border-bottom: 1px solid $border-light;
	
	.categories-scroll {
		white-space: nowrap;
		width: 100%;
		
		.category-list {
			display: inline-flex;
			padding: 0 $spacing-base;
			gap: $spacing-sm;
			
			.category-item {
				flex-shrink: 0;
				padding: $spacing-xs $spacing-base;
				background: $bg-page;
				border-radius: $radius-base;
				border: 1px solid transparent;
				transition: all $transition-fast;
				
				.category-name {
					font-size: $font-sm;
					color: $text-secondary;
					transition: all $transition-fast;
				}
				
				&.active {
					background: $primary-color;
					border-color: $primary-color;
					
					.category-name {
						color: #fff;
						font-weight: $font-medium;
					}
				}
			}
		}
	}
}
</style>
